package com.example.baselibrary.utlis


import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.os.Build
import com.example.baselibrary.receivers.RebootReceiver
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch

class RebootReceiverManager private constructor(private val context: Context) {

    private var rebootReceiver: RebootReceiver? = null
    private var isRegistered = false

    companion object {
        private var instance: RebootReceiverManager? = null

        fun getInstance(context: Context): RebootReceiverManager {
            if (instance == null) {
                instance = RebootReceiverManager(context.applicationContext)
            }
            return instance!!
        }
    }

    /**
     * 注册重启广播接收器
     */
    fun registerRebootReceiver(): Boolean {
        if (isRegistered) return true

        return try {
            rebootReceiver = RebootReceiver()
            val filter = IntentFilter().apply {
                addAction(Intent.ACTION_BOOT_COMPLETED)
                addAction("com.example.baselibrary.REBOOT_ACTION")
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
                    addAction(Intent.ACTION_MY_PACKAGE_REPLACED)
                }
            }
            context.registerReceiver(rebootReceiver, filter)
            isRegistered = true
            true
        } catch (e: Exception) {
            e.printStackTrace()
            false
        }
    }

    /**
     * 注销重启广播接收器
     */
    fun unregisterRebootReceiver() {
        if (!isRegistered || rebootReceiver == null) return

        try {
            context.unregisterReceiver(rebootReceiver)
            isRegistered = false
            rebootReceiver = null
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }


/**
 * 发送重启广播
 * @param delayMillis 延迟时间（毫秒），默认为0（立即发送）
 */
fun sendRebootBroadcast(delayMillis: Long = 0) {
    if (delayMillis <= 0) {
        // 立即发送广播
        val intent = Intent("com.example.baselibrary.REBOOT_ACTION")
        intent.setPackage(context.packageName)
        context.sendBroadcast(intent)
    } else {
        // 延迟发送广播
        CoroutineScope(Dispatchers.Main).launch {
            delay(delayMillis)
            val intent = Intent("com.example.baselibrary.REBOOT_ACTION")
            intent.setPackage(context.packageName)
            context.sendBroadcast(intent)
        }
    }
}


    /**
     * 检查是否已注册
     */
    fun isReceiverRegistered(): Boolean = isRegistered
}
